package com.zdb.n1.service.impl;

import com.zdb.n1.entity.ExerciseType;
import com.zdb.n1.payload.response.MessageResponse;
import com.zdb.n1.repository.ExerciseRecordRepository;
import com.zdb.n1.repository.ExerciseTypeRepository;
import com.zdb.n1.service.ExerciseTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ExerciseTypeServiceImpl implements ExerciseTypeService {

    @Autowired
    private ExerciseTypeRepository exerciseTypeRepository;
    
    @Autowired
    private ExerciseRecordRepository exerciseRecordRepository;

    @Override
    @Transactional
    public ExerciseType saveExerciseType(ExerciseType exerciseType) {
        return exerciseTypeRepository.save(exerciseType);
    }

    @Override
    public ExerciseType getExerciseTypeById(Long id) {
        return exerciseTypeRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("未找到运动类型"));
    }

    @Override
    public ExerciseType getExerciseTypeByName(String name) {
        return exerciseTypeRepository.findByName(name)
                .orElseThrow(() -> new RuntimeException("未找到运动类型"));
    }

    @Override
    public List<ExerciseType> getAllExerciseTypes() {
        return exerciseTypeRepository.findAll();
    }

    @Override
    public List<ExerciseType> getExerciseTypesByCategory(ExerciseType.Category category) {
        return exerciseTypeRepository.findByCategory(category);
    }

    /**
     * 检查运动类型是否有关联的运动记录
     * @param exerciseType 运动类型
     * @return 关联记录的数量
     */
    public long countRelatedRecords(ExerciseType exerciseType) {
        return exerciseRecordRepository.countByExerciseType(exerciseType);
    }

    @Override
    @Transactional
    public MessageResponse deleteExerciseType(Long id) {
        ExerciseType exerciseType = exerciseTypeRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("运动类型不存在"));
        
        // 检查是否有关联的运动记录
        long relatedRecordsCount = countRelatedRecords(exerciseType);
        
        if (relatedRecordsCount > 0) {
            // 如果有关联记录，则级联删除相关记录
            exerciseRecordRepository.deleteByExerciseType(exerciseType);
        }
        
        // 删除运动类型
        exerciseTypeRepository.deleteById(id);
        
        if (relatedRecordsCount > 0) {
            return MessageResponse.success("已删除该运动类型及其关联的" + relatedRecordsCount + "条运动记录");
        } else {
            return MessageResponse.success("运动类型删除成功");
        }
    }
} 